<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}" class="report-file-data">
    <el-row class="header-form"/>
    <div class="table-list">
      <div class="table-title-bar">
        <div class="table-title">
          <Title :is-show="true" :total="total" :title="fileName || '表格数据'"/>
        </div>
        <div :class="{'mobile-btn-box': showMobilePage}" class="report-file-btn-right">
          <el-button
            v-if="hasRouteAuth('total:report:chartcreate')"
            type="text"
            size="small"
            class="create-table btn-item"
            @click="createChart('add')">
            新建图表
            <img :src="CreateImg" alt="">
          </el-button>
          <export-button v-if="hasExportAuth" :export-api="exportApi" :export-name="exportName" class="btn-item" />
          <el-button
            v-if="hasRouteAuth('total:report:chartcreate') || hasRouteAuth('total:report:chartedit') || hasRouteAuth('total:report:chartdelete')"
            type="text"
            size="small"
            class="table-show-list btn-item"
            @click="showChartList">
            图表
          </el-button>
        </div>
      </div>
      <el-row>
        <el-col v-if="tabs && tabs.length > 0" class="tabs-wrap">
          <el-tabs v-if="reportType !== 2" v-model="activeID" @tab-click="handleClick">
            <el-tab-pane v-for="tabItem in tabs" :key="tabItem.id" :label="tabItem.tabName" :name="tabItem.id + ''"/>
          </el-tabs>
        </el-col>
        <el-col v-loading="listLoading" :class="{'borderradius': reportType === 2}" class="data-wrap">
          <!-- <p v-if="list && list.length < 1 && (!titles || titles.length === 0)" class="empty-text">暂无数据</p> -->
          <!-- v-if="list && titles && titles.length" -->
          <el-table
            v-if="list.length"
            ref="dataTable"
            :data="list"
            :fit="true"
            :excess-rows="500"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="table-header-cell-nobottom"
            hightlight-current-row
            class="data-table"
            @sort-change="sortMethod"
            @cell-dblclick="onCellDBClick"
            @filter-change="filterChange">
            <el-table-column type="index" align="right" width="60"/>
            <!-- firstTitle 是内品表格的逻辑，这里先注释 -->
            <!-- <el-table-column
              :label="firstTitle"
              :prop="firstTitle"
              min-width="100"
              align="left"
              show-overflow-tooltip
              sortable="custom"
              resizable>
              <template slot-scope="scope">
                {{ scope.row[0] }}
              </template>
            </el-table-column> :filter-method="filterHandler"-->
            <!-- :column-key="titleList[tIndex] ? titleList[tIndex].id.toString() :titleItem" -->
            <template v-for="(titleItem, tIndex) in titles">
              <el-table-column
                v-if="titleItem !== '_id'"
                :key="titleItem + tIndex"
                :label="titleItem"
                :prop="titleItem"
                :filter-multiple="true"
                :filters="titleList[tIndex] ? titleList[tIndex].items : []"
                :column-key="titleItem"
                min-width="130"
                align="left"
                show-overflow-tooltip
                sortable="custom"
                resizable>
                <template slot-scope="scope">
                  {{ scope.row[tIndex] }}
                </template>
              </el-table-column>
            </template>
          </el-table>
          <empty-placeholder v-else :empty-img-top="'0'" style="margin-bottom: 24px" />
        </el-col>
      </el-row>
      <el-row type="flex" justify="end" class="pagination-area">
        <el-col :span="12" style="padding: 10px; padding-left: 0;">
          <el-button :class="{'shrink-padding':showMobilePage}" type="primary" size="small" @click="clearFilter">重置所有筛选条件</el-button>
          <el-button
            :class="{'back-mobile':showMobilePage}"
            class="back-btn cancel-btn-style"
            type="info"
            size="small"
            @click="handleBack"
          >返回</el-button>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-pagination
            v-show="list.length > 0"
            :current-page="params.page"
            :page-size="params.perPage"
            :total="total"
            layout="total, prev, pager, next, jumper"
            @current-change="handleCurrentChange" />
        </el-col>
      </el-row>
    </div>
    <ChartList ref="chartListRef" @editChart="editChart"/>
    <CreateChart ref="createChartRef" :sheet-id="sheetId"/>
  </div>
</template>

<script>
import { getFileTabs, getFileData, getFileTitleList } from '@/api/reportManage';
import ExportButton from '@/components/ReportManage/reportExport';
import ChartList from '@/components/ReportManage/chartData/chartList';
import CreateChart from '@/components/ReportManage/chartData/createChart';
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import CreateImg from '@/assets/reportManage/add_icon.png';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';

import axios from 'axios';
export default {
  components: {
    ExportButton,
    Title,
    ChartList,
    CreateChart,
    EmptyPlaceholder
  },
  data() {
    return {
      CreateImg,
      list: [],
      firstTitle: '', // 单独获取第一个表头
      titles: [], // 去除表头的第一个 剩余的表头
      tabs: [],
      fileId: 0,
      fileName: '',
      activeID: '',
      listLoading: true,
      cacheData: {},
      listArr: [], // 获取筛选的值数组
      params: {
        page: 1,
        perPage: 250,
        list: ''
      },
      total: 0,
      titleList: [], // 获取表头的筛选数组
      cancelTitleHttp: null,
      cancelListHttp: null,
      sheetId: '',
      categoryName: '',
      reportType: 1,
      sortType: '',
      sortName: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    exportApi() {
      return `/admin/report/list/chart/export?id=${this.fileId}`;
    },
    exportName() {
      return this.fileName;
    },
    hasExportAuth() {
      const categoryName = this.categoryName;
      return this.hasAuth(categoryName, 'export');
    }
  },
  created() {
    this.initData();
  },
  beforeDestroy() {
    this.cacheData = {};
  },
  methods: {
    hasRouteAuth,
    hasAuth(categoryName, type = 'export') {
      let categoryExportAuth = '';
      if (categoryName !== '' && categoryName !== 'all') {
        if (categoryName.indexOf('财务') >= 0) {
          categoryExportAuth = `total:financereport:${type}`;
        } else if (categoryName.indexOf('内品') >= 0) {
          categoryExportAuth = `total:brandreport:${type}`;
        } else if (categoryName.indexOf('媒介') >= 0) {
          categoryExportAuth = `total:mediumreport:${type}`;
        }
      }
      const auth = categoryExportAuth !== '' ? this.hasRouteAuth(categoryExportAuth) : false;
      return this.hasRouteAuth(`total:report:${type}`) || auth;
    },
    handleClick(tab, event) {
      this.listLoading = true;
      this.cancelRequest(); // 取消请求
      if (this.list.length) { // 清除过滤
        this.$refs.dataTable.clearFilter();
      }
      this.resetData(); // 重置数据重新获取数据
    },
    getTabs() {
      return getFileTabs(this.fileId).then(({ data }) => {
        if (data) {
          this.tabs = data;
          const id = data.length ? data[0].id : ''; // 用于预防接口没有返回数据
          this.activeID = id + '';
          return this.activeID;
        }
      }, result => {
        return Promise.reject();
      });
    },
    getDataList(tabId, loadingShow, { page = 1, perPage, list }) {
      if (loadingShow) this.listLoading = true;
      this.sheetId = tabId;
      const params = { tabId: Number(tabId), page, perPage };
      if (list && list !== '') {
        params.list = JSON.stringify(list);
      }
      const source = axios.CancelToken.source();
      if (this.sortType) params.sortType = this.sortType;
      if (this.sortName) params.sortName = this.sortName;

      getFileData(this.fileId, params, source.token).then(({ data }) => {
        if (data) {
          this.list = data.items || [];
          this.titles = data.titles;
          // this.titles = data.titles.slice(1);
          // this.firstTitle = data.titles.shift();

          this.cacheData[tabId + ''] = data;
          this.params.page = data.page;
          this.params.perPage = data.perPage;
          this.total = data.total;
        } else {
          this.list = [];
          this.titles = [];
          this.firstTitle = '';
        }
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        this.listLoading = false;
        console.error(e);
      });
      this.cancelListHttp = source;
    },
    getTitleList(fileId, tabId, list) { // 获取表头筛选的数组
      const source = axios.CancelToken.source();
      const params = {
        tabId: Number(tabId)
      };
      if (list && list !== '') {
        params.list = JSON.stringify(list);
      }
      getFileTitleList(fileId, params, source.token).then(res => {
        const data = res.data;
        data.forEach(item => { // 将获取的数组形式进行转化成element组件所需要的格式
          if (item.items.length) {
            item.items = item.items.map((val, i) => {
              const obj = {
                id: item.id,
                text: val,
                value: val
              };
              return obj;
            });
          }
        });
        this.titleList = data;
      }, result => {
      }).catch(e => {
        console.error(e);
      });
      this.cancelTitleHttp = source;
    },
    cancelRequest() {
      if (this.cancelTitleHttp) {
        // console.log('cancelTitle');
        this.cancelTitleHttp.cancel();
      }
      if (this.cancelListHttp) {
        this.cancelListHttp.cancel();
      }
    },
    initData() {
      this.fileId = Number(this.$route.params.fileId) || 0;
      const name = this.$route.query.name;

      this.reportType = this.$route.query.reportType || 1;
      this.fileName = name ? decodeURIComponent(name) : '';
      this.categoryName = this.$route.query.categoryName;
      this.getTabs().then((tabID) => {
        this.getDataList(tabID || 0, true, this.params);
        this.getTitleList(this.fileId, tabID); // 获取表头筛选列表
      });
    },
    onCellDBClick(row, column, cell, event) {
      this.$copyText(cell.innerText).then(e => {
        this.$message({
          message: '单元格复制成功',
          type: 'success'
        });
      }, (e) => {
        console.error(e);
      });
    },
    filterChange(filters) { // 获取表头筛选的list值
      const keys = Object.keys(filters)[0] || '';
      const hasData = this.listArr.some(i => {
        if (i[keys]) {
          i[keys] = filters[keys];
        }
        return !!i[keys];
      });
      if (!hasData) {
        this.listArr.push(filters);
      }
      this.listArr = this.listArr.filter(i => {
        const itemkeys = Object.keys(i)[0] || '';
        return i[itemkeys].length;
      });
      this.params.list = this.listArr || [];
      this.params.page = 1;
      this.getTitleList(this.fileId, Number(this.activeID), this.listArr);
      this.getDataList(Number(this.activeID), true, this.params);
      this.isFilter = true;
    },
    // filterHandler(value, row, column) {
    //   console.log(row, value);
    //   return row.indexOf(value) !== -1;
    // },
    clearFilter() { // 清除筛选数据
      try {
        if (this.$refs.dataTable) {
          this.$refs.dataTable.clearFilter();
        }
        this.resetData(); // 重置数据
      } catch (error) {
        console.log(error);
      }
    },
    resetData() {
      this.listArr = [];
      // this.titleList = [];
      // this.list.splice(10, this.list.length);
      this.params.list = '';
      this.page = 1;
      // 重制排序，addTime: 2020-06-17
      this.sortType = '';
      this.sortName = '';
      if (this.$refs.dataTable) {
        this.$refs.dataTable.clearSort();
      }

      setTimeout(() => {
        this.getDataList(Number(this.activeID), true, this.params);
        this.getTitleList(this.fileId, Number(this.activeID));
      }, 0);
    },
    handleCurrentChange(toPage) {
      this.params.page = toPage;
      this.getDataList(Number(this.activeID), true, this.params);
    },
    showChartList() {
      const id = this.fileId;
      this.$refs.chartListRef.getData(true, id, this.sheetId);
    },
    createChart(type) {
      let fieldTitle = JSON.parse(JSON.stringify(this.titles));
      if (this.firstTitle !== '') {
        fieldTitle.unshift(JSON.parse(JSON.stringify(this.firstTitle)));
      }
      if (this.list.length === 0) {
        fieldTitle = [];
      }
      this.$refs.createChartRef.showDialog(type, fieldTitle);
    },
    // 编辑图表
    editChart(id) {
      let fieldTitle = JSON.parse(JSON.stringify(this.titles));
      if (this.firstTitle !== '') {
        fieldTitle.unshift(JSON.parse(JSON.stringify(this.firstTitle)));
      }
      if (this.list.length === 0) {
        fieldTitle = [];
      }
      setTimeout(() => {
        this.$refs.createChartRef.showDialog('edit', fieldTitle, id);
      }, 300);
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortType = a.order === 'ascending' ? 1 : -1;
        this.sortName = a.prop;
      } else {
        this.sortType = '';
        this.sortName = '';
      }
      this.getDataList(Number(this.activeID), true, this.params);
    },
    handleBack() {
      this.$router.push({
        name: 'total'
      });
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .report-file-data {
    margin: 16px;
    background-color: #fff;
    padding: 24px;
    min-height: 100vh;
    .table-list {
      border-radius: 10px;
      .el-row {
        padding: 0;
        & ::v-deep {
          .el-table {
            font-size: 14px;
            border:1px solid rgba(235,238,253,1);
            border-radius:0px 12px 12px 12px;
            &::before{
              display: none;
            }

          }
          .borderradius {
            .el-table {
              border-radius:12px 12px 12px 12px;
            }
          }
        }
      }
      .tabs-wrap {
        background: white;
        & ::v-deep {
          .el-tabs__header {
            margin-bottom: 0;
            border-bottom: none;
          }
          .el-tabs__nav-wrap::after {
            display: none
          }
          .el-tabs__active-bar {
            display: none;
          }
          .el-tabs__item {
            // border-radius:0px 12px 0px 0px;
            padding: 0 34px;
            border:1px solid rgba(235,238,253,1);
            border-right: none;
            font-size:16px;
            border-radius:0;
            font-family:PingFangSC-Medium,PingFang SC;
            &:nth-child(2) {
              border-top-left-radius: 12px;
            }
            &:last-child {
              border-top-right-radius: 12px;
              border-right:1px solid rgba(235,238,253,1);
            }
            &.is-active {
              color: #fff;
              background:linear-gradient(142deg,rgba(116,167,255,1) 0%,rgba(64,110,255,1) 100%);
            }
          }
        }
      }
      .data-wrap {
        background: white;
        // min-height: 100px;
        .empty-text {
          text-align: center;
          margin-top: 45px;
        }
      }
    }
  }
  .table-title-bar {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin-bottom: 16px;
    .table-title {
      flex: 1;
      width: 50%;
    }
    .report-file-btn-right {
      display: flex;
      flex-wrap: wrap;
      .btn-item {
        margin-left: 16px;
      }
    }
    .mobile-btn-box {
      margin-top: 10px;
      .create-table, .table-show-list {
        margin-left: 0;
      }
      .table-show-list {
        margin-top: 10px;
      }
    }
    .table-show-list {
      width:80px;
      height:32px;
      border-radius:4px;
      border:1px solid rgba(64,110,255,1);
    }
    .create-table {
      height:32px;
      background:rgba(239,243,251,1);
      border-radius:4px;
      padding: 0;
      font-size:14px;
      font-family:PingFangSC-Regular,PingFang SC;
      font-weight:400;
      line-height:32px;
      padding: 0 16px;
      img {
        position: relative;
        top: 2px;
        width: 16px;
        height: 16px;
        margin-left: 10px;
      }
    }
  }
  .el-table-filter { // 设置筛选下拉框的滚动条
    max-height: 500px;
    overflow-y: scroll;
  }
  .data-table {
    .el-table__column-filter-trigger i { // 设置筛选下箭头颜色
      color: #888 !important;
    }
  }
  .shrink-padding {
    padding: 7px 10px;
  }
  .back-mobile {
    margin: 10px 0 0;
  }
  .mobile-detail-wrap {
    margin: 0;
    padding: 12px;
  }
</style>
<style lang="scss">
  .el-table-filter__list {
    max-height: 300px;
  }
  .el-table-filter {
    .el-scrollbar__wrap {
      overflow-x: hidden;
      margin-bottom: 0px !important;
    }
    // .el-table-filter__bottom {
    //   button:last-child {
    //     display: none;
    //   }
    // }
  }
</style>
